﻿#region Usings

using System;
using InfoService.Utils;
using MediaPortal.Configuration;
using MediaPortal.GUI.Library;
using WeatherConnector;
using WeatherConnector.Data;
using WeatherConnector.Expections;

#endregion

namespace InfoService.Weather
{
    public static class WeatherService
    {
        #region Config Properties
        private static int _refreshInterval;
        public static int RefreshInterval
        {
            get { return _refreshInterval; }
            set
            {
                logger.WriteLog("Set WeatherRefreshInterval to " + value, LogLevel.Debug, InfoServiceModul.InfoService); 
                _refreshInterval = value;
            }
        }

        private static bool _updateOnStartup;
        public static bool UpdateOnStartup
        {
            get { return _updateOnStartup; }
            set
            {
                logger.WriteLog("Set WeatherUpdateOnStartup to " + value, LogLevel.Debug, InfoServiceModul.InfoService); 
                _updateOnStartup = value;
            }
        }
        #endregion

        #region Fields
        private static readonly Logger logger = Logger.GetInstance();
        private static WeatherConnector.Weather _weather;
        private static TemperatureFormat _tempFormat;
        private static string _locationCode;
        #endregion

        #region Properties
        public static bool Enabled { get; set; }
        public static WeatherConnector.Weather Weather
        {
            get
            {
                if (_weather.WeatherData != null)
                {

                    return _weather;
                }
                return new WeatherConnector.Weather();
            }
        }
        public static DateTime LastRefresh { get; set; }

        public static string CurrentLocationId { get; set; }

        #endregion

        #region Methods
        public static bool SetupWeather(string locationCode, TemperatureFormat tempFormat, string partnerId, string licenseKey)
        {
            WeatherConnector.Weather.SetLoginCreditials(partnerId, licenseKey);
            try
            {
                LogEvents.OnDebug += LogEvents_OnDebug;
                LogEvents.OnError += LogEvents_OnError;
                LogEvents.OnWarning += LogEvents_OnWarning;
                LogEvents.OnInfo += LogEvents_OnInfo;
                _weather = new WeatherConnector.Weather(locationCode, tempFormat);
                //_weather = new WeatherConnector.Weather(_weatherFileXml);
                _locationCode = locationCode;
                _tempFormat = tempFormat;
                Enabled = true;
                return true;
            }
            catch (WeatherNoPartnerIDOrLicenseKeyExpection ex)
            {
                logger.WriteLog(ex.Message, LogLevel.Error, InfoServiceModul.Weather);
                return false;

            }
            catch (WeatherNoLocationIDExpection ex)
            {
                logger.WriteLog(ex.Message, LogLevel.Error, InfoServiceModul.Weather);
                return false;
            }

        }

        //public static void UpdateWeatherData(string locationId)
        //{
        //    _weather = new WeatherConnector.Weather(_weatherFileXml);
        //    if (_weather.UpdateWeatherData())
        //    {
        //        SetProperties();
        //    }
        //    else
        //    {
        //        logger.WriteLog("Update weather from file " + _weatherFileXml + " unsuccessful. Now trying to update weather directly from weather.com", LogLevel.Warning, InfoServiceModul.Weather);
        //        _weather = new WeatherConnector.Weather(locationId, _tempFormat);
        //        if (_weather.UpdateWeatherData())
        //        {
        //            SetProperties();
        //        }
        //        else
        //        {
        //            logger.WriteLog("Update of weather unsuccesfull. Check the errors and warnings above!", LogLevel.Error, InfoServiceModul.Weather);
        //        }
        //    }

        //}

        public static bool UpdateWeatherData(string locationId)
        {
            _weather.LocationId = locationId;
            if (_weather.UpdateWeatherData())
            {
                LastRefresh = DateTime.Now;
                logger.WriteLog("Update of weather successful. Now setting up properties...", LogLevel.Info,
                                InfoServiceModul.Weather);
                SetProperties();
                return true;
            }
            else
            {
                logger.WriteLog("Update of weather unsuccesfull. Check the errors and warnings above!", LogLevel.Error,
                                InfoServiceModul.Weather);
                return false;
            }

        }

        private static void SetProperties()
        {
            _weather.WeatherData.TodayCondition = Localize(_weather.WeatherData.TodayCondition);
            string tmp = _weather.WeatherData.TodayFeelsLikeTemperature;
            _weather.WeatherData.TodayFeelsLikeTemperature = tmp +
                                                             _weather.WeatherEntities.TemperatureFormat.
                                                                 GetStringValue();
            tmp = _weather.WeatherData.TodayHumidity;
            _weather.WeatherData.TodayHumidity = tmp + "%";
            tmp = _weather.WeatherData.TodayTemperature;
            _weather.WeatherData.TodayTemperature = tmp +
                                                    _weather.WeatherEntities.TemperatureFormat.GetStringValue();
            tmp = _weather.WeatherData.TodayMaxTemperature;
            _weather.WeatherData.TodayMaxTemperature = tmp +
                                                       _weather.WeatherEntities.TemperatureFormat.GetStringValue();
            tmp = _weather.WeatherData.TodayMinTemperature;
            _weather.WeatherData.TodayMinTemperature = tmp +
                                                       _weather.WeatherEntities.TemperatureFormat.GetStringValue();
            tmp = _weather.WeatherData.TodayUvIndex;
            _weather.WeatherData.TodayUvIndex = Localize(tmp);
            for (int i = 0; i <= 4; i++)
            {
                if (i < _weather.WeatherData.WeatherForecast.Count)
                {
                    tmp = _weather.WeatherData.WeatherForecast[i].MaxTemperature;
                    _weather.WeatherData.WeatherForecast[i].MaxTemperature = tmp +
                                                                             _weather.WeatherEntities.TemperatureFormat.
                                                                                 GetStringValue();
                    tmp = _weather.WeatherData.WeatherForecast[i].MinTemperature;
                    _weather.WeatherData.WeatherForecast[i].MinTemperature = tmp +
                                                                             _weather.WeatherEntities.TemperatureFormat.
                                                                                 GetStringValue();
                    tmp = _weather.WeatherData.WeatherForecast[i].Day.Humidity;
                    _weather.WeatherData.WeatherForecast[i].Day.Humidity = tmp + "%";
                    tmp = _weather.WeatherData.WeatherForecast[i].Night.Humidity;
                    _weather.WeatherData.WeatherForecast[i].Night.Humidity = tmp + "%";
                    _weather.WeatherData.WeatherForecast[i].Day.Condition =
                        Localize(_weather.WeatherData.WeatherForecast[i].Day.Condition);
                    _weather.WeatherData.WeatherForecast[i].Night.Condition =
                        Localize(_weather.WeatherData.WeatherForecast[i].Night.Condition);
                }
                else
                {
                    WeatherForecast wfc = new WeatherForecast();
                    wfc.Date = _weather.WeatherData.WeatherForecast[i - 1].Date.AddDays(1);
                    wfc.MaxTemperature = "N/A" + _weather.WeatherEntities.TemperatureFormat.GetStringValue();
                    wfc.MinTemperature = "N/A" + _weather.WeatherEntities.TemperatureFormat.GetStringValue();
                    wfc.Sunrise = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                    wfc.Sunset = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                    wfc.Day = new WeatherDay("N/A",
                                             "N/A",
                                             "N/A",
                                             "N/A%",
                                             "");
                    wfc.Night = new WeatherDay("N/A",
                                             "N/A",
                                             "N/A",
                                             "N/A%",
                                             "");
                    _weather.WeatherData.WeatherForecast.Add(wfc);
                    i++;
                }
            }

        }


        private static string Localize(string ustring)
        {
            string localizedString;
            string returnString = String.Empty;
            foreach (string estring in ustring.Split(new[] {" "}, StringSplitOptions.None))
            {
                localizedString = String.Empty;
                if ((String.Compare(estring, "T-Storms", true) == 0) || (String.Compare(estring, "T-Storm", true) == 0))
                {
                    localizedString = GUILocalizeStrings.Get(370);
                }
                else if (String.Compare(estring, "Partly", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x173);
                }
                else if (String.Compare(estring, "Mostly", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x174);
                }
                else if ((String.Compare(estring, "Sunny", true) == 0) || (String.Compare(estring, "Sun", true) == 0))
                {
                    localizedString = GUILocalizeStrings.Get(0x175);
                }
                else if ((String.Compare(estring, "Cloudy", true) == 0) || (String.Compare(estring, "Clouds", true) == 0))
                {
                    localizedString = GUILocalizeStrings.Get(0x176);
                }
                else if (String.Compare(estring, "Snow", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x177);
                }
                else if (String.Compare(estring, "Rain", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x178);
                }
                else if (String.Compare(estring, "Light", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x179);
                }
                else if (String.Compare(estring, "AM", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x17a);
                }
                else if (String.Compare(estring, "PM", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x17b);
                }
                else if (((String.Compare(estring, "Showers", true) == 0) ||
                          (String.Compare(estring, "Shower", true) == 0)) ||
                         (String.Compare(estring, "T-Showers", true) == 0))
                {
                    localizedString = GUILocalizeStrings.Get(380);
                }
                else if (String.Compare(estring, "Few", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x17d);
                }
                else if ((String.Compare(estring, "Scattered", true) == 0) ||
                         (String.Compare(estring, "Isolated", true) == 0))
                {
                    localizedString = GUILocalizeStrings.Get(0x17e);
                }
                else if (String.Compare(estring, "Wind", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x17f);
                }
                else if (String.Compare(estring, "Strong", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x180);
                }
                else if (String.Compare(estring, "Fair", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x181);
                }
                else if (String.Compare(estring, "Clear", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x182);
                }
                else if (String.Compare(estring, "Early", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x183);
                }
                else if (String.Compare(estring, "and", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x184);
                }
                else if (String.Compare(estring, "Fog", true) == 0 ||
                         (String.Compare(estring, "Foggy", true) == 0))
                {
                    localizedString = GUILocalizeStrings.Get(0x185);
                }
                else if (String.Compare(estring, "Haze", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(390);
                }
                else if (String.Compare(estring, "Windy", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x187);
                }
                else if (String.Compare(estring, "Drizzle", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x188);
                }
                else if (String.Compare(estring, "Freezing", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x189);
                }
                else if (String.Compare(estring, "N/A", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x18a);
                }
                else if (String.Compare(estring, "Mist", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x18b);
                }
                else if (String.Compare(estring, "High", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x31f);
                }
                else if (String.Compare(estring, "Low", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x31e);
                }
                else if (String.Compare(estring, "Moderate", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x216);
                }
                else if (String.Compare(estring, "Late", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x229);
                }
                else if (String.Compare(estring, "Very", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x22a);
                }
                else if (String.Compare(estring, "Heavy", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x197);
                }
                else if (String.Compare(estring, "N", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x217);
                }
                else if (String.Compare(estring, "E", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x218);
                }
                else if (String.Compare(estring, "S", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x219);
                }
                else if (String.Compare(estring, "W", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x21a);
                }
                else if (String.Compare(estring, "NE", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x21b);
                }
                else if (String.Compare(estring, "SE", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(540);
                }
                else if (String.Compare(estring, "SW", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x21d);
                }
                else if (String.Compare(estring, "NW", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x21e);
                }
                else if (String.Compare(estring, "Thunder", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x21f);
                }
                else if (String.Compare(estring, "NNE", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x220);
                }
                else if (String.Compare(estring, "ENE", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x221);
                }
                else if (String.Compare(estring, "ESE", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x222);
                }
                else if (String.Compare(estring, "SSE", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x223);
                }
                else if (String.Compare(estring, "SSW", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x224);
                }
                else if (String.Compare(estring, "WSW", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x225);
                }
                else if (String.Compare(estring, "WNW", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x227);
                }
                else if (String.Compare(estring, "NNW", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x228);
                }
                else if (String.Compare(estring, "VAR", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x22c);
                }
                else if (String.Compare(estring, "CALM", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x22d);
                }
                else if (((String.Compare(estring, "Storm", true) == 0) ||
                          (String.Compare(estring, "Gale", true) == 0)) ||
                         (String.Compare(estring, "Tempest", true) == 0))
                {
                    localizedString = GUILocalizeStrings.Get(0x257);
                }
                else if (String.Compare(estring, "in the Vicinity", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(0x22f);
                }
                else if (String.Compare(estring, "Clearing", true) == 0)
                {
                    localizedString = GUILocalizeStrings.Get(560);
                }
                if (localizedString == String.Empty)
                {
                    localizedString = estring;
                }
                returnString = returnString + localizedString + " ";
            }
            return returnString;
        }
#endregion

        #region Log Events

        static void LogEvents_OnInfo(WeatherArgs weatherArguments)
        {
            logger.WriteLog(weatherArguments, LogLevel.Info, InfoServiceModul.Weather);
        }

        static void LogEvents_OnWarning(WeatherArgs weatherArguments)
        {
            logger.WriteLog(weatherArguments, LogLevel.Warning, InfoServiceModul.Weather);
        }

        static void LogEvents_OnError(WeatherArgs weatherArguments)
        {
            logger.WriteLog(weatherArguments, LogLevel.Error, InfoServiceModul.Weather);
        }

        static void LogEvents_OnDebug(WeatherArgs weatherArguments)
        {
            logger.WriteLog(weatherArguments, LogLevel.Debug, InfoServiceModul.Weather);
        }
        #endregion
    }
}